<?php

namespace Xin\Menu\ThinkPHP;

use think\Service;
use Xin\Menu\Contracts\Factory as MenuFactory;
use Xin\Menu\Contracts\Generator as MenuGenerator;
use Xin\Menu\Generators\DefaultGenerator;
use Xin\Menu\MenuManager;

class MenuServiceProvider extends Service
{
    /**
     * 注册服务
     * @return void
     */
    public function register()
    {
        $this->registerGenerator();

        $this->registerMenuManager();
    }

    /**
     * 注册菜单管理器
     * @return void
     */
    protected function registerMenuManager()
    {
        $this->app->bind([
            'menu' => MenuFactory::class,
            MenuFactory::class => MenuManager::class,
            MenuManager::class => function () {
                $manager = new MenuManager(
                    $this->app->config->get('menu')
                );

                $this->registerDrivers($manager);

                $manager->setContainer($this->app);
                return $manager;
            },
        ]);

        $this->app->bind('menu.driver', function () {
            return $this->app['menu']->menu();
        });
    }

    /**
     * 注册菜单驱动
     */
    protected function registerDrivers(MenuManager $manager)
    {
        $manager->extend('model', function ($name, $config) {
            return new ModelRepository($config);
        });
    }

    /**
     * 注册生成器
     * @return void
     */
    protected function registerGenerator()
    {
        $this->app->bind([
	        'menu.generator' => MenuGenerator::class,
	        MenuGenerator::class => DefaultGenerator::class,
        ]);
    }
}
